package com.xianyun.site.support.executor.handle.smtp;

import com.aliyuncs.dm.model.v20151123.BatchSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.xianyun.common.core.filter.FilterChain;
import com.xianyun.site.support.common.FilterChainFactory;
import com.xianyun.site.support.common.exception.SmtpException;
import com.xianyun.site.support.common.utils.SpringBeanUtil;
import com.xianyun.site.support.convertor.SmtpConvertor;
import com.xianyun.site.support.domain.model.SmtpMessage;
import com.xianyun.site.support.dto.SmtpReceiveCmd;
import com.xianyun.site.support.executor.filter.smtp.EmailOneMinNotRepeatFilter;
import com.xianyun.site.support.executor.filter.smtp.EmailSendTooMuchFilter;
import com.xianyun.site.support.executor.handle.smtp.v20201108.config.SmtpSendType;
import org.springframework.util.Assert;

/**
 * @author mac_zyj
 */
public class SmtpContent {
    /**
     * 责任链配置
     */
    private final FilterChain<SmtpReceiveCmd> filterChain;

    {
        filterChain = FilterChainFactory.buildFilterChain(
                EmailOneMinNotRepeatFilter.class,
                EmailSendTooMuchFilter.class
        );
    }

    /**当前策略*/
    private  BaseSmtpStrategy currentStrategy;

    public SmtpContent(String type) {
        Assert.notNull(type,"请确认邮件类型是否正确");
        if (null!= SmtpSendType.getSmtpStrategyByType(type)){
            currentStrategy= SpringBeanUtil.getBean(SmtpSendType.getSmtpStrategyByType(type));
        }
    }

    /**
     * 生成简单邮件请求
     * @param smtpParams 邮件参数
     * @return 简单邮件对象
     */
    public SingleSendMailRequest sendSingleMailRequest(SmtpReceiveCmd smtpParams){
        filterChain.doFilter(smtpParams);
        if (null!=currentStrategy){
            SmtpMessage smtpMessage = SmtpConvertor.toEntity(smtpParams.getSmtpMessage());
            return currentStrategy.sendSingleMailRequest(smtpMessage);
        }
        throw new SmtpException("请确认邮件类型是否正确");
    }

    /**
     * 生成模板邮件请求
     * @return 模板邮件请求
     */
    public BatchSendMailRequest sendBatchMailRequest() {
        return currentStrategy.sendBatchMailRequest();
    }
}
